const express = require('express')
const app = express()
const expressJWT = require('express-jwt')
const config = require('./config')

const joi = require('joi')

// 跨域问题
const cors = require('cors');
app.use(cors())

// 数据格式
app.use(express.json()) 

// 配置错误级别中间件
app.use((req,res,next)=>{
  res.cc = (err,status = 1) => {
      res.send({
          status,
          message: err instanceof Error ? err.message:err,
      })
  }
  next()
})

// 在路由之前配置解析 token 的中间件
app.use(expressJWT(
  {
    secret : config.jwtSecretKey,
    algorithms : config.algorithms,
  }).unless({
    path:[/^\/user/]
  }))

// 注册用户路由模块，并为用户路由模块搭载统一前缀
const userRouter = require('./router/user')
app.use('/user',userRouter)

const InfoRouter = require('./router/userInfo')
app.use('/user',InfoRouter)

const Router = require('./router/userInfo')
app.use('/info',Router)

// 错误中间件
app.use(function (err, req, res, next) {
  if (err instanceof joi.ValidationError) return res.cc(err)
  if(err.name === 'UnauthorizedError') return res.cc('身份认证失败！')
  res.cc(err)
  }
)

app.listen(8080,()=>{
  console.log('api server running at http://127.0.0.1:8080')
})